<?php
/**
*	Moviecontroller
*
*	- get movies from imdb
*	- manipulate data
*
*	@method storeMovies($firsttime = false): add movies to db
*	@method addMovie($id): add single movie to db
*	@method adjustTimestamp(): after IMDB-scan, adjust latestUpdate-setting
*	@method countMoviesFromUser($id)
*	@method getMovies(): get movies from DB
*	@method getMoviesFromIMDB(): scan IMDB website (requires simple_html_dom.php)
*	@method getSeenMovies($userid)
*	@method printMovies($userid = null): HTML Table
*	@method removeMovieForUser($userid, $movieid)
*	@method updateMovieRanking($idInDB, $movie)
*
*/
require_once(ABSOLUTEPATH . "/libs/simple_html_dom.php");

class Moviecontroller {
	
	private $dbcon;

    public function  __construct($_dbcon)
    {
        $this->dbcon = $_dbcon;
        
        //check if list needs to be updated
        $timestamp = strtotime($this->dbcon->getSettingValue("lastUpdate"));
        $nowminusthirty = strtotime("-30 minutes", $timestamp);
       
        //if last update is more than 30 minutes ago, scan IMDB site
        if($timestamp < $nowminusthirty)
        	$this->storeMovies();
    }
   
    /**
    *	Function called upon if latest update is more than 30 minutes ago
    *
    *	@param bool $firsttime: if firsttime, don't try to get movies from DB
    */
    public function storeMovies($firsttime = false) {
       
        $movielist = $this->getMoviesFromIMDB();
     
        if(!$firsttime)
        	$currentMovies = $this->getMovies();
        
        if($currentMovies)
        {
        	$aidArray = array();
        
	        foreach($currentMovies as $movieDB)
	        {
	        	$aidArray[$movieDB->getTitel()] = $movieDB->getID();
	        }     
        
        }
        
       
        foreach($movielist as $movieIMDB)
        {
        	
        	$id = -1;
        	//if old movie, update SQL-table:movie_ranking_time(id, ranking, timestamp)
        	if($aidArray && $aidArray[$movieIMDB->getTitel()])
        	{
        		//echo $movieIMDB->getTitel();
        		$idInDB = $aidArray[$movieIMDB->getTitel()];
        		$this->updateMovieRanking($idInDB, $movieIMDB);
        	}
        	else{
        		//if new movie, add to movie & add ranking to SQL-table:movie_ranking_time
        		$idInDB = $this->addMovie($movieIMDB);
        		$this->updateMovieRanking($idInDB, $movieIMDB);
        	}
        		
       	}
       	
       	//update lastUpdated-setting
       	$this->adjustTimestamp();

	
		//ON SUCCESS / ON FAILURE??        

    }
    /**
    *	@return affected row
    */
    
	public function addMovie($movie){
	
		$values = array($movie->getTitel(), floatval($movie->getScore()), $movie->getLink());
	    $columns= array("titel", "rate", "link");
	    $returnid = true;
	    
	    return $this->dbcon->insertQuery("movie", $values, $columns, $returnid);
	}
    
    public function updateMovieRanking($idInDB, $movie){
    
    	$values = array($idInDB, floatval($movie->getRanking()));
	    $columns= array("movie_id", "ranking");

   		$this->dbcon->insertQuery("movie_ranking_time", $values, $columns);
    }
    
    public function adjustTimestamp(){
    	$latestStamp = $this->dbcon->getLatestTimestamp();
    	$this->dbcon->updateSettingValue("lastUpdate", $latestStamp);
    }
	/**
	*	Called in HTML (content.html)
	*
	*	@return TABLE
	*/
    public function printMovies($userid = null){

        $movies = $this->getMovies();
        $seenmovies = array();
        
        //if registered user
        if($userid && $this->getSeenMovies($userid)!= null)
        	$seenmovies = $this->getSeenMovies($userid);
        	
        
        $trlist = array();

        foreach($movies as $movie){
        
            $movieid = intval($movie->getID());
            $input = "<tr id='". $movieid ."' ";
            if(in_array($movieid, $seenmovies))
            	$input .= "class='checked' ";
            $input .= ">";
            $input .= "<td class='rank'>" . $movie->getRanking() . "</td>";
            $input .= "<td class='title'><span>" . $movie->getTitel() . "</span>  <a href='http://imdb.com".$movie->getLink()."' target='_blank'><img src='./img/icon-new-window.gif' /></a></td>";
            $input .= "<td class='rating'>" . $movie->getScore() . "</td>";
            $input .= "</tr>";

            $trlist[] = $input;
        }

        return $trlist;

    }
    /**
    *	Called by printMovies
    *	If there are no movies in DB, calls storeMovies($firsttime = true)
    *
    *	@return array $movieList;
    */
    public function getMovies(){
        $movieList = array();
                
        $result = $this->dbcon->selectQuery("movie");
        
        if(!$result)
        {
        	$firsttime = true;
        	$result = $this->storeMovies($firsttime);
        	        	
        }
        
        $i = 0;
        while ($row = $result->fetch_object()){
            
            $titel = $row->titel;
            $score = $row->rate;
            $link = $row->link;
            $id = $row->id;
            $whereclause = array( "movie_id" => $id);
            $ranking = $this->dbcon->selectQueryLastUpdate("movie_ranking_time", "ranking", $whereclause);
            if(!is_string($ranking))
            	$ranking = 0; //error: multiple timestamps with same value
			//echo "ranking: " . $ranking; 
            $movie = new movie($ranking, $titel, $score, $link, "n");
            $movie->setID($id);
            $movieList[] = $movie;
        }
        return $movieList;
    }

    public function addMovieForUser($userid, $movieid){
        
        $table = "user_movie";
        $values = array(intval($userid), intval($movieid));
        //log result
        $this->dbcon->insertQuery("user_movie", $values);
    }

    public function removeMovieForUser($userid, $movieid) {

        $table = "user_movie";
        $whereclause = "WHERE userid = '". $userid ."' && movieid = '". $movieid ."'";

        $query = $this->dbcon->deleteQuery($table, $whereclause);

    }

    public function getSeenMovies($userid)
    {

        $table = "user_movie";
        $columns = array("movieid");
        $whereclause = array("userid" => $userid);
        $resultset = $this->dbcon->selectQuery($table, $columns, $whereclause);
        
        if(!$resultset || !is_object($resultset))
        	return null;
        try{
        	while ($row = $resultset->fetch_object()){
            	$movieList[] = intval($row->movieid);
       		}
        	return $movieList;

        }
        catch(Exception $e)
        {
        	print_r($e);
        }
        
    }
    
    /**
    *	Script-function to scan IMDB website and get top 250
    *	Requires simple_html_dom (found in libs folder)
    */
    
    private function getMoviesFromIMDB(){

	    //$set_time_limit = set_time_limit (  60 );
	
	    $html = file_get_html("http://www.imdb.com/chart/top");
	
	
	    $list = $html->find('tr[valign=top]');
	    $movieList = array();
	   
	    foreach($list as $element)
	    {
	       
	        $ranking = str_replace(".", "", $element->find('font b', 0)->innertext);
	        $score = $element->find('font', 1)->innertext;
	        $titel = $element->find('font', 2)->find('a', 0)->innertext;
	        $pattern = '/\(.+\)/';
	        $matches;
	        $brackarray = array("(", ")");
	        preg_match($pattern, $element->find('font', 2)->innertext, $matches);
	        $year = str_replace($brackarray, "" , $matches[0]);
	        $link = $element->find('font', 2)->find('a', 0)->href;
	
	        $movie = new movie($ranking, $titel, $score, $link, $year);
	        
	        $movieList[] = $movie;
	
	    }

    return $movieList;

	}
	
	public function countMoviesFromUser($_id){
		return $this->dbcon->countRows("user_movie", null, array("userid" => $_id));
	}
	
	
	/** CHECK IF MOVIE IS STILL IN TOP250 */
}

?>